package com.ronx.scs.controller;

import com.ronx.scs.service.ChangePasswordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.provisioning.UserDetailsManager;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class AccountController {

    //    @Autowired
    private ChangePasswordService changePasswordService;

    @Autowired
    private UserDetailsManager userDetailsManager;


    @RequestMapping(value = "/account/changePassword.do", method = RequestMethod.GET)
    public void showChangePasswordPage() {
    }

//    @RequestMapping(value = "/account/changePassword.do", method = RequestMethod.POST)
//    public String submitChangePasswordPage(@RequestParam("password") String newPassword) {
//        Object principal = SecurityContextHolder.getContext().
//            getAuthentication().getPrincipal();
//        String username = principal.toString();
//
//        if (principal instanceof UserDetails) {
//            username = ((UserDetails) principal).getUsername();
//        }
//
//        changePasswordService.changePassword(username, newPassword);
//        SecurityContextHolder.clearContext();
//        return "redirect:home.do";
//    }

    public String submitChangePasswordPage(@RequestParam("oldpassword") String oldPassword, @RequestParam("password") String newPassword) {
        userDetailsManager.changePassword(oldPassword, newPassword);
        SecurityContextHolder.clearContext();
        return "redirect:home.do";
    }

}
